import math
from timer import Timer as HpTimer

#用二分法
eps = 1e-7
def SqrtByBisection(n):
    if n < 0 : return n

    low, high, mid = 0, n, (0+n)/2

    while(1):
        if abs(mid*mid-n)<=eps:
            break
        elif mid*mid > n:
            high = mid
        else:
            low = mid
        mid = (low+high) / 2
    return mid

#牛顿迭代法，https://blog.csdn.net/album_gyd/article/details/81416398
def SqrtByNewton(n):
    val = n
    while(1):
        last = val
        val =(val + n/val) / 2
        if abs(val - last) <= eps:
            break
    return val


if __name__ == "__main__":

    t1 = HpTimer()

    #二分查找法，慢且精度没有牛顿法高
    #6.240172754256249e-05
    #1.4368818842037416e-05
    #SqrtByBisection(10)

    #2.牛顿迭代法，快且精度高
    #2.586387391566735e-05
    #1.1905592754831002e-05
    print(SqrtByNewton(10))
    print(t1.secondsDiff())


    t2 = HpTimer()
    print(math.sqrt(10))
    print(t2.secondsDiff())

